package com.example.springboot.sse;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

@Slf4j
@RestController
@RequestMapping("/sse")
public class SseController {


    @GetMapping("/getClient")
    public SseEmitter getClient(String requestId){

        SseEmitter emitter = new SseEmitter(30_000L);
        emitter.onCompletion(() -> {
            log.info("answerStream:onCompletion:chatAiRequestId={}:{}",requestId,"连接完成");
        });
        emitter.onTimeout(() -> {
            log.error("answerStream:onTimeout:chatAiRequestId={}:{}",requestId,"超时");
        });
        emitter.onError(throwable -> {
            log.error("answerStream:onError:chatAiRequestId={}:{}",requestId,throwable.toString());
        });
        new Thread(()->{
            for (int i = 0; i < 30; i++) {
                try {
                    Thread.sleep(100L);
                    SseResponseEvent<ZjuEduChatAnswerPush> event = new SseResponseEvent<>();
                    ZjuEduChatAnswerPush push = new ZjuEduChatAnswerPush();
                    push.setChatAiRequestId(requestId);
                    push.setContent("测试"+i);
                    event.setData(push);
                    emitter.send(JSON.toJSONString(event), MediaType.APPLICATION_JSON);
//                    emitter.send(SseEmitter.event().data(push).build());
//                    emitter.send("测试"+i);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
        return emitter;
    }
}
